<template>
    <div>
        <div class="container">
            <el-button type="warning" :icon="CirclePlusFilled" style="margin-bottom: 10px" @click="visibleIn = true">新增入住</el-button>
            <el-button type="danger" :icon="CirclePlusFilled" style="margin-bottom: 10px" @click="visibleOut = true">新增出院</el-button>

        <el-table
          :data="tableData"
          :preserve-expanded-content="true"
          style="height: calc(100vh - 300px);"
        >
          <el-table-column label="姓名" prop="elderName" />
          <el-table-column label="年龄" prop="age" />
          <el-table-column label="性别" prop="gender" />
          <el-table-column label="健康状态" prop="healthStatus" />
          <el-table-column label="入住时间" prop="checkInDate" />
          <el-table-column label="出院时间" prop="checkOutDate" />
          <el-table-column label="出院原因" prop="dischargeReason" />
          <el-table-column label="最近录入时间" prop="updateTime" />
          <el-table-column label="操作" width="200px">
                <template #default="{ row: flowRow }">
                        <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(flowRow)">
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(flowRow)">
                            删除
                        </el-button>
                </template>
            </el-table-column>
        </el-table>
          <el-pagination v-if="hasPagination" :page-size="page.size" :background="false"
                         :page-sizes="[10, 20, 50, 100]"  @size-change="handleSizeChange"
                         layout="sizes,prev, pager, next" :total="page.total" @current-change="handleCurrentChange" style="margin-top: 10px" />
        </div>
        <el-dialog :title="'新增入住'" v-model="visibleIn" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeInDialog">
            <TableEdit :form-data="rowData" :options="inOptions" :edit="isEdit" :update="updateData" />
        </el-dialog>
        <el-dialog :title="'新增出院'" v-model="visibleOut" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeOutDialog">
            <TableEdit ref="tableEditRef" :form-data="rowData" :options="outOptions" :edit="isEdit" :update="updateData" />
        </el-dialog>



        <el-dialog :title="'编辑'" v-model="visibleFull" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeFullDialog">
            <TableEdit :form-data="rowData" :options="fullOptions" :edit="isEdit" :update="updateFullData" />
        </el-dialog>

        <el-dialog title="查看详情" v-model="visibleDetails" width="700px" destroy-on-close>
            <TableDetail :data="viewData"></TableDetail>
        </el-dialog>
        <el-dialog title="查看记录 详情" v-model="visibleFlowDetails" width="700px" destroy-on-close>
            <TableDetail :data="viewFlowData"></TableDetail>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="finance-management">

import { ref, reactive,onMounted,watch,nextTick } from 'vue';


import { ElMessage, ElMessageBox } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { fetchElderData,fetchElderInfoList,saveElderData,delElderDataById,getElderInfoByIdCard,saveElderDataByIdCard } from '@/api';


import TableDetail from '@/components/table-detail.vue';
import { Finance } from '@/types/dto';
import { FormOption, FormOptionList } from '@/types/form-option';
import { Delete, Edit, View, Refresh } from '@element-plus/icons-vue';

const hasPagination = ref(true);
const visibleIn = ref(false);
const visibleOut = ref(false);
const visibleFull = ref(false);

const isEdit = ref(false);
const rowData = ref({});


onMounted(async () => {
    initSelect();
});

const initSelect =  async () => {
    const res = await fetchElderInfoList();

    const opts = res.data.map(item => ({
        label: item.elderName + '(' + item.idCard + ')',
        value: item.idCard
    }));
    
    const projectItem = outOptions.value.list.find(item => item.prop === 'elderName');
    if (projectItem) {
        projectItem.opts = opts;
    }
}

// 添加对 TableEdit 组件的引用
const tableEditRef = ref();
const idCard = ref('');


// 监听 rowData 中 elderName 的变化
watch(
  () => rowData.value.elderName,
  async (newVal, oldVal) => {
    if (newVal && newVal !== oldVal) {
      try {
        // 假设 elderName 包含身份证号或有其他方式关联
        // 如果需要通过其他方式获取身份证号，请相应调整
        // 这里需要根据实际情况获取身份证号
        if (visibleOut.value) {
            idCard.value = newVal;
        }

        // if (idCard.value) {
        //   const elderInfo = await getElderInfoByIdCard(idCard.value);
        //   // 更新 rowData
        //   rowData.value = { ...rowData.value, ...elderInfo.data };
        // }
      } catch (error) {
        console.error('获取 elder 信息失败:', error);
      }
    }
  }
);


const handleCurrentChange = (val: number) => {
    page.index = val;
    page.currentPage = val;
    getData();
};

const handleSizeChange = (val: number) => {
    page.size = val;
    page.index = 1;
    page.currentPage = 1;
    getData();
};

const page = reactive({
    total: 0,
    index: 1,
    size: 50,
    hasPagination: true,
    layout: 'prev, pager, next,total',
    currentPage: 1,
    pageCount: 1
})
const tableData = ref<[]>();
const getData = async () => {
    await initSelect();
    const res = await fetchElderData(page.index, page.size);
    tableData.value = res.data.content;
    page.index = res.data.number + 1;
    page.total = res.data.totalElements;
    page.size = res.data.size;
    page.pageCount = res.data.totalPages;
};

getData();


// 新增/编辑入院弹窗相关
let inOptions = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'input', prop: 'elderName', label: '姓名' , required: true },

        { type: 'input', prop: 'idCard', label: '身份证号' , required: true  },
        { type: 'number', prop: 'age', label: '年龄' , required: true  },
        { type: 'select', label: '性别', prop: 'gender', required: true, opts: [
            { label: '男', value: '男' },
            { label: '女', value: '女' },
        ]},
        { type: 'select', prop: 'healthStatus', label: '健康状态' , required: true , opts: [
            { label: '正常', value: '正常' },
            { label: '失能', value: '失能' },
            { label: '半失能', value: '半失能' }
        ]  },
        { type: 'date',format: 'YYYY-MM-DD', prop: 'checkInDate', label: '入住时间' , required: true  },

    ]
})

// 新增/编辑出院记录弹窗相关
let outOptions = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'select', prop: 'elderName', label: '姓名' , required: true  },
        { type: 'date',format: 'YYYY-MM-DD', prop: 'checkOutDate', label: '出院时间' , required: true  },
        { type: 'input', prop: 'dischargeReason', label: '出院原因' , required: true  },

    ]
})


// 新增/编辑记录弹窗相关
let fullOptions = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'select', prop: 'elderName', label: '姓名' , required: true  },
        { type: 'input', prop: 'idCard', label: '身份证号' , required: true , disabled: false },
        { type: 'number', prop: 'age', label: '年龄' , required: true , disabled: false },
        { type: 'input', prop: 'gender', label: '性别' , required: true , disabled: false },
        { type: 'select', prop: 'healthStatus', label: '健康状态' , required: true , opts: [
            { label: '正常', value: '正常' },
            { label: '失能', value: '失能' },
            { label: '半失能', value: '半失能' }
        ]  , disabled: false },

        { type: 'date',format: 'YYYY-MM-DD', prop: 'checkInDate', label: '入住时间' , required: true, disabled: false  },
        { type: 'date',format: 'YYYY-MM-DD', prop: 'checkOutDate', label: '出院时间' , required: true  },
        { type: 'input', prop: 'dischargeReason', label: '出院原因' , required: true  },

    ]
})

const handleEdit = (row) => {
    isEdit.value = true;
    visibleFull.value = true;
    rowData.value = { ...row };
    
};

const closeFullDialog = () => {
    visibleFull.value = false;
    isEdit.value = false;
};

const updateFullData = async (data) => {

    await saveElderData(data);
    
    if (!isEdit.value) {
        ElMessage.success('新增成功');
    } else {
        ElMessage.success('编辑成功');
    }
    closeFullDialog();
    getData();
};

const updateData = async (data) => {
    if (idCard.value && visibleOut.value) {
        data.idCard = idCard.value;
        await saveElderDataByIdCard(data);
    } else {
        await saveElderData(data);
    }
    if (!isEdit.value) {
        ElMessage.success('新增成功');
    } else {
        ElMessage.success('编辑成功');
    }
    closeInDialog();
    closeOutDialog();
    getData();
};


const closeInDialog = () => {
    visibleIn.value = false;
    isEdit.value = false;
};

const closeOutDialog = () => {
    visibleOut.value = false;
    isEdit.value = false;
};

// 查看详情弹窗相关
const visibleDetails = ref(false);
const visibleFlowDetails = ref(false);
const viewFlowData = ref({
    row: {},
    list: []
});
const viewData = ref({
    row: {},
    list: []
});


// 删除记录

const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除吗？', '提示', {
        type: 'warning'
    })
        .then(async () => {
            await delElderDataById(row.id);
            await getData();
            ElMessage.success('删除成功');
        })
        .catch(() => { });
    
};


</script>

<style>

.container {
    min-height: calc(100vh - 150px) !important; 
    box-sizing: border-box;
    background: #fff;
    padding: 20px;
    overflow: auto;
}

.el-table.no-header-bg th {
    height: 40px;
    background-color: #fff !important;
    font-weight: normal;
    text-align: center !important;

}
.el-table th.el-table__cell  {
    text-align: center !important;
}

.el-table td.el-table__cell{
    text-align: center !important;
}

</style>